package android.gpsmessenger;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.content.DialogInterface;
import android.content.Intent;
import android.app.AlertDialog;
import android.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.ViewGroup;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CurrentTripFragment extends Fragment
{
	private Button new_trip_button, choose_trip_button, location_button;
	private Button frequency_button, record_button, upload_button;
	private Button help_button, sos_button, message1_button, message2_button;

	private TripManager tripManager;
	private TripList trips;
	private Trip selectedTrip;
	private boolean tripSelected = false;
	private boolean recordSelected = false;
	private EditText trip_name;
	private int selectedFrequency;
	private String tripName;
	
	private String[] frequencies = {"2 sec", "30 sec", "1 min", "2 min", 
    		"5 min", "10 min", "15 min", "30 min", "60 min"};
    
	private MessengerLocator messengerLocator;
	private Messenger emailMessenger;
	private Messenger textMessenger;
	
	private ContactList contacts;
	private ContactManager contactManager;
	
	public void onCreate (Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		selectedFrequency = -1;
		tripManager = new TripManager(getActivity());
		selectedTrip = new Trip();
		trips = new TripList();
		
		tripName = getActivity().getIntent().getStringExtra("selected_name");
		Log.i("selectedTrip", "selectedTrip: " + tripName);
		
		MessengerLocator messengerLocator = new MessengerLocator();
		textMessenger = messengerLocator.createMessenger(getActivity(), "text");
		emailMessenger = messengerLocator.createMessenger(getActivity(), "email");
		
		contactManager = new ContactManager(getActivity());
		contacts = contactManager.load();
	}
		
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
		return inflater.inflate(R.layout.fragment_current_trip, container, false);
	}
	
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.fragment_home_menu, menu);
	}
	
	public boolean onOptionsItemSelected (MenuItem item) 
	{
        Intent intent = new Intent(getActivity(), MainActivity.class);
		if (item.getItemId() == R.id.menu_home) 
		{
	        getActivity().startActivity(intent);
		}

		return true;
	}
	
	public void onResume() 
	{
		super.onResume();

		if (tripName != null)
		{
			trips = tripManager.load();
			selectedTrip = trips.getTrip(tripName);
			tripSelected = true;
			
			buttonsEnabled(true);
			trip_name.setText(selectedTrip.getName());
		}
	}
	
	public void onPause() 
	{
	    super.onPause(); 
	}	
		
	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		getActivity().setContentView(R.layout.fragment_current_trip);
		
		trip_name = (EditText) getActivity().findViewById(R.id.tripName);
		new_trip_button = (Button) getActivity().findViewById(R.id.new_trip_button);
		choose_trip_button = (Button) getActivity().findViewById(R.id.choose_trip_button);
		record_button = (Button) getActivity().findViewById(R.id.record_button);
		upload_button = (Button) getActivity().findViewById(R.id.upload_button);
		frequency_button = (Button) getActivity().findViewById(R.id.frequency_button);
		help_button = (Button) getActivity().findViewById(R.id.help_button);
		sos_button = (Button) getActivity().findViewById(R.id.sos_button);
		message1_button = (Button) getActivity().findViewById(R.id.send_message1_button);
		message2_button = (Button) getActivity().findViewById(R.id.send_message2_button);
		location_button = (Button) getActivity().findViewById(R.id.send_location_button);
		
		new_trip_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				Intent newTripIntent = new Intent(getActivity().getApplicationContext(), TripProfileActivity.class);		
			    startActivity(newTripIntent);
			}
 		});		

		choose_trip_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				Intent tripListIntent = new Intent(getActivity().getApplicationContext(), TripListActivity.class);	
			    startActivity(tripListIntent);
			}
 		});	
	
		upload_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{

			}
 		});	
		
		record_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{

			}
 		});	
		
		sos_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("sos"), "sos", tripManager.getSOSLocationMessage());
			}
 		});	
		
		help_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("help"), "help", new MessageList().getHelpMessage().toString());
			}
 		});	
		
		message1_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("help"), "message1", new MessageList().getMessage1().toString());
			}
 		});	
		
		message2_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				textMessenger.send(getRecipients("help"), "message2", new MessageList().getMessage2().toString());
			}
 		});	
		
		location_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				emailMessenger.send(getRecipients("friend"), "send location", tripManager.getLocationMessage());
			}
 		});	
		
		frequency_button.setOnClickListener(new OnClickListener() 
		{
 			@Override
			public void onClick(View v) 
			{
 				AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
 				alt_bld.setTitle("Select Record Frequency");

 				alt_bld.setSingleChoiceItems(frequencies , -1,
 				new DialogInterface.OnClickListener() 
 				{
 					public void onClick(DialogInterface dialog, int item) 
 					{
 						selectedFrequency = item;
 					}
 				});
 				
 				alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() 
 				{
 					@Override
 					public void onClick(DialogInterface dialog, int which) 
 					{
 						Toast.makeText(getActivity().getApplicationContext(), "Selected record frequency: " + frequencies[selectedFrequency], Toast.LENGTH_SHORT).show();
 						Log.i("selectedFrequency", "selectedFrequency1: " + selectedFrequency);
 						dialog.dismiss();
 					}
 				});
 				
 				alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
 				{
 					@Override
 					public void onClick(DialogInterface dialog, int which) 
 					{
 						dialog.dismiss();
 					}
 				});
 				
 				AlertDialog alert = alt_bld.create();
 				alert.show();
			}
 		});	

		buttonsEnabled(false);
    }
	
	public String[] getRecipients (String type)
	{
		List<Contact> recipients = new ArrayList<Contact>(100);
		List<String> contactInfo = new ArrayList<String>(100);
		String[] to = new String[contactInfo.size()]; //{"5556"};
		Contact sosContact;
		
		if (type.equals("help"))
		{
			if (tripName != null )
				recipients = selectedTrip.getContacts().getHelpContacts().getContactList();
			else
				recipients = contactManager.load().getHelpContacts().getContactList();
		}
		else if (type.equals("friend"))
		{
			if (tripName != null )
				recipients = selectedTrip.getContacts().getFriendContacts().getContactList();
			else
				recipients = contactManager.load().getFriendContacts().getContactList();
		}
		else if (type.equals("sos"))
		{
			if (tripName != null )
				sosContact = selectedTrip.getContacts().getSOSContact();
			else
				sosContact = contactManager.load().getSOSContact();
			
			recipients.add(sosContact);
		}	
		
		if (type.equals("friend"))
		{
			for (Contact c : recipients)
			{
				contactInfo.add(c.getEmail());
			}
		}
		else 
		{
			for (Contact c : recipients)
			{
				contactInfo.add(c.getPhone());
			}
		}
		
		to = contactInfo.toArray(new String[recipients.size()]);

		return to;
	}
	
	public String getSelectedFrequency()
	{
		if (selectedFrequency != -1)
		{
			Log.i("selectedFrequency", "selectedFrequency: " + frequencies[selectedFrequency]);
			return frequencies[selectedFrequency];
		}
		return null;
	}
	
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
	    MenuItem end = menu.findItem(R.id.menu_end);
		if (recordSelected ) {
			end.setEnabled(true);
		} else {
			end.setEnabled(false);	
		}
	}
	
	public void buttonsEnabled(boolean flag)
	{
		if  (flag)
		{
			frequency_button.setEnabled(true);
			upload_button.setEnabled(true);
			record_button.setEnabled(true);
		}
		else
		{
			frequency_button.setEnabled(false);
			upload_button.setEnabled(false);
			record_button.setEnabled(false);			
		}
	}
	
}

